<script setup lang="ts">
import { ref, watch } from 'vue';
import { useAppStore } from '@/store/modules/app';
import { useEcharts } from '@/hooks/common/echarts';

defineOptions({ name: 'PerformanceMonitor' });

const appStore = useAppStore();
const currentTimeRange = ref('realtime'); // realtime, 1h, 1d, 1w

// 使用useEcharts钩子初始化图表
const { domRef, updateOptions } = useEcharts(() => ({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross',
      label: {
        backgroundColor: '#6a7985'
      }
    }
  },
  legend: {
    data: ['CPU使用率', 'GPU使用率', '内存使用率'],
    top: 0
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    top: '15%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: [] as string[]
  },
  yAxis: {
    type: 'value',
    max: 100,
    axisLabel: {
      formatter: '{value}%'
    }
  },
  series: [
    {
      color: '#8e9dff',
      name: 'CPU使用率',
      type: 'line',
      smooth: true,
      emphasis: {
        focus: 'series'
      },
      data: [] as number[]
    },
    {
      color: '#26deca',
      name: 'GPU使用率',
      type: 'line',
      smooth: true,
      emphasis: {
        focus: 'series'
      },
      data: []
    },
    {
      color: '#ff7d00',
      name: '内存使用率',
      type: 'line',
      smooth: true,
      emphasis: {
        focus: 'series'
      },
      data: []
    }
  ]
}));

// 生成模拟数据
function generateMockData(range: string) {
  let labels = [];
  let cpuData = [];
  let gpuData = [];
  let memoryData = [];

  switch (range) {
    case 'realtime':
      // 实时数据 - 过去30分钟
      for (let i = 30; i >= 0; i--) {
        const now = new Date();
        now.setMinutes(now.getMinutes() - i);
        labels.push(`${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`);
        cpuData.push(55 + Math.random() * 20);
        gpuData.push(70 + Math.random() * 25);
        memoryData.push(60 + Math.random() * 15);
      }
      break;
    case '1h':
      // 1小时数据 - 每2分钟一个点
      for (let i = 30; i >= 0; i--) {
        const now = new Date();
        now.setMinutes(now.getMinutes() - i * 2);
        labels.push(`${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`);
        cpuData.push(50 + Math.random() * 25);
        gpuData.push(65 + Math.random() * 30);
        memoryData.push(55 + Math.random() * 20);
      }
      break;
    case '1d':
      // 1天数据 - 每小时一个点
      for (let i = 24; i >= 0; i--) {
        const now = new Date();
        now.setHours(now.getHours() - i);
        labels.push(`${now.getHours().toString().padStart(2, '0')}:00`);
        cpuData.push(40 + Math.random() * 30);
        gpuData.push(60 + Math.random() * 35);
        memoryData.push(50 + Math.random() * 25);
      }
      break;
    case '1w':
      // 1周数据 - 每天一个点
      const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
      for (let i = 6; i >= 0; i--) {
        const now = new Date();
        now.setDate(now.getDate() - i);
        labels.push(days[now.getDay()]);
        cpuData.push(45 + Math.random() * 25);
        gpuData.push(55 + Math.random() * 35);
        memoryData.push(55 + Math.random() * 20);
      }
      break;
  }

  return {
    labels,
    cpuData,
    gpuData,
    memoryData
  };
}

// 更新图表数据
function updateChartData() {
  const data = generateMockData(currentTimeRange.value);

  updateOptions(opts => {
    opts.xAxis.data = data.labels;
    opts.series[0].data = data.cpuData;
    opts.series[1].data = data.gpuData;
    opts.series[2].data = data.memoryData;

    return opts;
  });
}

// 切换时间范围
function changeTimeRange(range: string) {
  currentTimeRange.value = range;
  updateChartData();
}

// 初始化图表数据
function init() {
  updateChartData();
}

// 监听时间范围变化
watch(currentTimeRange, () => {
  updateChartData();
});

// 初始化
init();
</script>

<template>
  <NCard :bordered="false" class="card-wrapper h-full">
    <div class="flex items-center justify-between mb-4">
      <h3 class="text-xl font-semibold flex items-center">
        <SvgIcon icon="mdi-chart-line" class="mr-2 text-primary" />
        系统性能监控
      </h3>
      <div class="flex gap-2">
        <NButton
          v-for="range in [
            { key: 'realtime', label: '实时' },
            { key: '1h', label: '1小时' },
            { key: '1d', label: '1天' },
            { key: '1w', label: '1周' }
          ]"
          :key="range.key"
          :type="currentTimeRange === range.key ? 'primary' : 'default'"
          size="small"
          @click="changeTimeRange(range.key)"
        >
          {{ range.label }}
        </NButton>
      </div>
    </div>
    <div ref="domRef" class="h-320px overflow-hidden"></div>
  </NCard>
</template>

<style scoped></style>